package com.liujit.web.advisor;

import cn.hutool.core.lang.tree.TreeNode;
import com.liujit.common.domain.result.ErrorResult;
import com.liujit.common.domain.result.Result;
import com.liujit.common.utils.JacksonUtil;
import com.liujit.common.utils.ReqUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @description: 返回值封装
 * @author: liujun
 * @create: 2020/12/31 4:57 下午
 **/
@Slf4j
@ControllerAdvice
public class ResponseAdvisor implements ResponseBodyAdvice<Object> {

    private static final String FEIGN_REQUEST_START = "/feign";

    private static final String SWAGGER_REQUEST_START = "/swagger-resources";

    private static final String SWAGGER_DOC_REQUEST_START = "/v2/api-docs";

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        HttpServletRequest request = ReqUtil.getRequest();
        String uri = request.getRequestURI();
        if (uri.startsWith(FEIGN_REQUEST_START) || uri.startsWith(SWAGGER_REQUEST_START) || uri
                .startsWith(SWAGGER_DOC_REQUEST_START)) {
            return false;
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
            ServerHttpResponse response) {
        if (body instanceof ErrorResult) {
            ErrorResult errorResult = (ErrorResult) body;
            return Result.builder().code(errorResult.getCode()).msg(errorResult.getMsg()).data(errorResult.getErrors())
                    .build();
        }
        if (body instanceof Result) {
            return body;
        }
        if (body instanceof String) {
            return JacksonUtil.toJsonString(Result.success(body));
        }
        if (body instanceof TreeNode) {
            return JacksonUtil.toJsonString(Result.success(body));
        }
        return Result.success(body);
    }
}
